package cn.tpshion.vm.base.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForStateless;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.tpshion.vm.base.interceptor.AuthInterceptor;
import cn.tpshion.vm.base.interceptor.RequestInterceptor;
import cn.tpshion.vm.common.model.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@Configuration
public class BaseConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestInterceptor())
                .excludePathPatterns("/error")
                .excludePathPatterns("/actuator/**")
                .excludePathPatterns("/favicon.ico")
                .addPathPatterns("/**");

        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(getAuthInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/auth/login", "/sse/**", "/login")
                .excludePathPatterns("/error")
                .excludePathPatterns("/actuator/**")
                .excludePathPatterns("/favicon.ico");
    }

    public SaInterceptor getAuthInterceptor(){
        return new AuthInterceptor(handle -> {
            StpUtil.checkLogin();
            String username = (String) StpUtil.getLoginId();
            if(StringUtils.isNoneBlank(username)){
                RequestContext.setUsername(username);
            }
        });
    }

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForStateless();
    }
}
